<?

	include("inc/config.inc.php");

	$startdate = mysqli_real_escape_string($con,$_POST[startdate]);
	$enddate = mysqli_real_escape_string($con,$_POST[enddate]);
	$starttime = mysqli_real_escape_string($con,$_POST[starttime]);
	$endtime = mysqli_real_escape_string($con,$_POST[endtime]);
	$description = mysqli_real_escape_string($con,$_POST[description]);

	// Check both dates are in same year period
	if (substr($startdate, 0, 4) == substr($enddate, 0, 4))
		$yearperiod = substr($startdate, 0, 4);
	else
		die("Error 21 - Date insert discrepancy - please contact support.");


	// Calculate how many days are required for this request (Remove weekends and bank holidays)
	$days = daysCalculation($startdate, $enddate, $starttime, $endtime);

	// Calculate how many days left
	$daysLeft = getEntitlement($yearperiod) - daysUsed($yearperiod);
 
	// Check request isn't for more days then are available
 	if ($days > $daysLeft)
 		die("Error 22 - Date count mismatch - please contact support");

	// Get Managers details
	$manager = getManager();

	// Insert pending request into database
	mysqli_query($conn, "INSERT into requests SET user='$_SESSION[user]', description='$description', startdate='$startdate', enddate='$enddate', starttime='$starttime', endtime='$endtime', yearperiod='$yearperiod', days='$days', status='Pending', statusdate=now(), statusmessage='Awaiting approval from $manager'");

	// Humans date format for email
	$startdate = date("d-m-Y", strtotime($startdate));
	$enddate = date("d-m-Y", strtotime($enddate));

	// Email manager
	niceMail(getManagerEmail($_SESSION[user]), 'Holiday request from '. $_SESSION[user] .' requires your approval', "A holiday request has been submitted by " . $_SESSION[user] ." that requires your approval.\n\r\n\rFrom: $startdate ($starttime)\rTo: $enddate ($endtime)\n\r\n\rPlease visit " . $config[url] . " to accept or reject the request.");

	// Redirect back to main page, passing the id of request so that we can highlight it
	header("Location:main.php?newreq=" . mysqli_insert_id($conn));

?>
